<?php
namespace api\modules\shop\controllers;

use common\service\ConstantService;
use common\models\User;
use common\service\WechatService;
class IndexController extends ShopBaseController
{

    public function actionIndex(){
        echo '首页B端111';exit;
    }

    /**
     * 获取用户Token
     */
    public function actionAutoLogin(){
        if($this->isAjax() && $this->isGet() ){
            $code = $this->get('code');
            $appid = \Yii::$app->params['wechat']['appid'];
            $secret = \Yii::$app->params['wechat']['secret'];
            $request = WechatService::getWechatOpenid($code,$appid,$secret);
            $request = json_decode($request,true);
            if(isset($request['errcode'])){
                return $this->renderJson([],'code无效',ConstantService::$response_fail);
            }
            $openid = $request['openid'];
            $user = User::find(['openid'=>$openid])->asArray()->one();
            if(!$user){
                //用户不存在入库
                $user_model = new User();
                $data['openid'] = $openid;
                $user_model->setAttributes($data);
                if(!($user_model->save())){
                    return $this->renderJson([],'用户信息存储失败',ConstantService::$response_fail);
                }
                return $this->renderJson([],'该用户未授权',ConstantService::$response_fail_auth);

            }
//            if(empty($user['nickname']) && empty($user['avatarurl'])){
//                return $this->renderJson([],'该用户未授权',ConstantService::$response_fail_auth);
//            }
            //最终都返回Token
            $token = base64_encode(base64_encode($openid).'-'.$this->salt);
            return $this->renderJson($token,'操作成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

}